<template>
  <div class="searchResult">
    <el-tabs v-model="tabName" @tab-click="handleTabClick">
      <el-tab-pane :lazy="true" label="帖子" name="帖子">
        <el-empty v-if="postList.length === 0" description="暂无相关帖子" />
        <post
          v-for="item in postList"
          v-else
          :key="item.id"
          class="post"
          :post-info="item"
          :like="handleLike"
          :dislike="handleDislike"
          :collect="handleCollect"
          :report="handleReport"
          @click.native="goPostDetail(item)"
        />
      </el-tab-pane>
      <el-tab-pane :lazy="true" label="用户" name="用户">
        <el-empty v-if="userList.length === 0" description="暂无相关用户" />
        <div v-for="item in userList" :key="item.id" class="userInfoCard" @click="goUserInterface(item)">
          <div class="left">
            <el-image :src="baseUrl + item.avatarUrl" />
            <div class="left-inside">
              <h3>{{ item.nickName }}</h3>
              <span>{{ item.replyCount }}回答</span>
              <span>{{ item.postCount }}帖子</span>
              <span>{{ item.followerCount }}关注者</span>
            </div>
          </div>
          <div class="right">
            <template v-if="parseInt(userId) !== item.id">
              <el-button
                v-if="userFocusInfoMap[item.id] ? userFocusInfoMap[item.id].isFocus === 0 : true"
                type="primary"
                plain
                icon="el-icon-plus"
                @click.stop="handleFocus(item, userFocusInfoMap[item.id] ? userFocusInfoMap[item.id].isFocus : undefined)"
              >关注</el-button>
              <el-button
                v-else
                type="info"
                plain
                icon="el-icon-check"
                @click.stop="handleFocus(item, userFocusInfoMap[item.id] ? userFocusInfoMap[item.id].isFocus : undefined)"
              >已关注</el-button>
            </template>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import post from '@/components/post'
import { savePostFeedback, updatePostFeedback } from '@/api/postfeedback'
import { getPostVoList } from '@/api/post'
import { mapGetters } from 'vuex'
import { saveUserFocusInfo, updateUserFocusInfo, getUserFocusInfoList } from '@/api/userFocusInfo'
import { getUserInfoVoList } from '@/api/userInfo'
import { formatDateTime } from '@/utils/dateUtil'
import pubsub from 'pubsub-js'
export default {
  name: 'SearchResult',
  components: {
    post
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      postList: [],
      userList: [],
      pageNum: 1,
      pageSize: 5,
      pubsubId: undefined,
      searchValue: this.$route.query.searchValue,
      tabName: '帖子',
      userFocusInfoMap: {}
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  watch: {
    $route() {
      this.searchValue = this.$route.query.searchValue
      this.getPostVoList()
      this.getUserInfoVoList()
    }
  },
  beforeMount() {
    this.getPostVoList()
    this.subscribeUpdatePostVoList()
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pubsubId)
  },
  methods: {
    goUserInterface(userInfo) {
      this.$router.push({
        path: '/userInterface',
        query: {
          userId: userInfo.user.id
        }
      })
    },
    async handleFocus(userInfo, isFocus) {
      try {
        if (isFocus !== undefined) {
          await updateUserFocusInfo({
            beFocusedUserId: userInfo.id,
            isFocus: isFocus === 0 ? 1 : 0,
            focusDate: formatDateTime(new Date())
          })
        } else {
          await saveUserFocusInfo({
            beFocusedUserId: userInfo.id,
            isFocus: 1,
            focusDate: formatDateTime(new Date())
          })
        }
      } catch (error) {
        console.log(error)
      }
      this.getUserFocusInfoList()
    },
    async getUserInfoVoList() {
      const searchParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searches: [{
          key: 'ui.nick_name',
          rule: 'like',
          value: this.searchValue
        }]
      }
      const { data } = await getUserInfoVoList(searchParam)
      this.userList = data.list
    },
    handleTabClick(tab) {
      switch (tab.name) {
        case '帖子':
          this.pageNum = 1
          this.pageSize = 5
          this.getPostVoList()
          break
        case '用户':
          this.pageNum = 1
          this.pageSize = 5
          this.getUserFocusInfoList()
          break
        default:
          break
      }
    },
    getUserFocusInfoList() {
      getUserFocusInfoList().then(res => {
        const userFocusInfoList = res.data
        this.userFocusInfoMap = userFocusInfoList?.reduce((cur, value) => {
          cur[value.beFocusedUserId] = value
          return cur
        }, {})
        this.userFocusInfoMap = this.userFocusInfoMap ? this.userFocusInfoMap : {}
        this.getUserInfoVoList()
      }, err => {
        console.log(err)
      })
    },
    subscribeUpdatePostVoList() {
      this.pubsubId = pubsub.subscribe('updateData', () => {
        this.pageSize += 5
        if (this.tabName === '帖子') this.getPostVoList()
        else this.getUserInfoVoList()
      })
    },
    async getPostVoList() {
      const searchParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searches: [
          {
            key: 'title',
            rule: 'like',
            value: this.searchValue
          }
        ]
      }
      const { data } = await getPostVoList(searchParam)
      this.postList = data.list
    },
    async handleLike(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isLike: 0
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    async handleDislike(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isLike: 1
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    async handleCollect(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isCollect: postInfo.isCollect === 0 ? 1 : 0
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    handleReport(postInfo) {
      this.$router.push({
        path: '/report',
        query: {
          postId: postInfo.id
        }
      })
    },
    goPostDetail(item) {
      this.$router.push({
        path: '/postDetail',
        query: {
          postId: item.id
        }
      })
    }
  }
}
</script>

<style lang="scss">
.searchResult {
  .el-tabs__nav-wrap {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgb(255, 255, 255);
    height: 50px;
  }
  .el-tabs__content {
    padding: 10px;
    margin: 10px auto;
    border-radius: 15px;
    width: 1150px;
    min-width: 1150px;
    background: rgba(133, 185, 254, 0.738);
    box-shadow: 0 0 6px black;
    .el-empty__description p {
      color: black;
      font-weight: bold;
    }
  }
  .el-tabs__header {
    margin: 0;
  }
}
</style>

<style lang="scss" scoped>
.searchResult {
  padding: 0 0 10px 0;
  .el-tabs {
    .post {
      margin: 10px auto;
      &:hover {
        cursor: pointer;
        outline: 5px solid rgb(36, 36, 36);
      }
    }
    .userInfoCard {
      display: flex;
      background-color: white;
      border-radius: 10px;
      margin-bottom: 10px;
      padding: 10px;
      align-items: center;
      &:hover {
        box-shadow: 0 0 10px black;
        cursor: pointer;
      }
      .left {
        display: flex;
        align-items: center;
        flex-grow: 1;
        .el-image {
          border-radius: 50%;
          width: 80px;
          height: 80px;
        }
        .left-inside {
          margin-left: 10px;
          h3 {
            margin: 0 0 10px 0;
          }
          span {
            margin-right: 10px;
            color: rgb(153, 153, 153);
          }
        }
      }
      .right {
        flex-shrink: 1;
        .el-button {
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
